import { Module } from '@nestjs/common'
import { TypeOrmModule } from "@nestjs/typeorm";
import * as path from "path";
import * as dayjs from 'dayjs';
import { FileService } from './file.service'
import { FileController } from './file.controller'
import { MulterModule } from "@nestjs/platform-express"
import { SnowflakeId } from "@libs/snowflake.id"
import { diskStorage } from "multer"
import { Request } from 'express'
import { Express } from "express"
import { checkDirAndCreate, getExtName } from "@utils/file";
import { FileEntity } from "@entities/file.entity";
import { isImage } from "@utils/file";

@Module({
    imports: [
        TypeOrmModule.forFeature([FileEntity]),
        MulterModule.register({
            // 配置文件上传后的文件夹路径
            storage: diskStorage({
                destination: (req: Request, file: Express.Multer.File, callback: (error: (Error | null), filename: string) => void) => {
                    const extName = getExtName(file.originalname).toLowerCase(); //获取文件后缀名
                    const source = req.headers['source']; //附件来源
                    const category = isImage(extName) ? 'images' : extName // 文件分类
                    const filePath = `public/uploads/${category}/${dayjs().format('YYYY-MM-DD')}`;
                    file['source'] = source;
                    file['filePath'] = filePath
                    checkDirAndCreate(filePath); // 判断文件夹是否存在，不存在则自动生成
                    return callback(null, `./${filePath}`);
                },

                // 在此处自定义保存后的文件名称
                filename(req: Request, file: Express.Multer.File, callback: (error: (Error | null), filename: string) => void) {
                    try {
                        const fileId = SnowflakeId.generate(); //获取文件后缀名
                        const extName = getExtName(file.originalname); //生成文件名
                        const filename = `${fileId}.${extName}`; //生成文件id
                        file['fileId'] = fileId;
                        file['savePath'] = path.join(file['filePath'], filename);
                        file['suffix'] = getExtName(filename);
                        return callback(null, filename);
                    } catch (error) {
                        console.error(error);
                    }
                }
            })
        })
    ],
	controllers: [FileController],
	providers: [FileService]
})
export class FileModule {}
